import { defineComponent, ref } from "vue";
// https://github.com/brix/crypto-js
import CryptoJS from "crypto-js";
import useCopy from "@/hook/useCopy";
import BothInputTemplate from "@/components/Template/BothInputTemplate.vue";

import { ElButton } from "element-plus";
import cssModule from "./index.module.scss";

export default defineComponent({
  setup() {
    const originStr = ref("");
    const encryptRes = ref("");

    // 加密
    const encrypt = (data: string, key: string) => {
      const _key = CryptoJS.enc.Utf8.parse(key);
      const iv = CryptoJS.lib.WordArray.random(16);
      const encrypted = CryptoJS.AES.encrypt(data, _key, {
        iv,
        mode: CryptoJS.mode.CTR,
        padding: CryptoJS.pad.Pkcs7
      });
      return encrypted.ciphertext.toString(CryptoJS.enc.Base64) + ":" + iv.toString(CryptoJS.enc.Hex);
    };

    // 解密
    const decode = (data: string, key: string) => {
      const parts = data.split(":");
      const _key = CryptoJS.enc.Utf8.parse(key);
      const ciphertext = CryptoJS.enc.Base64.parse(parts[0]);
      const iv = CryptoJS.enc.Hex.parse(parts[1]);
      const decrpted = CryptoJS.AES.decrypt(ciphertext.toString(CryptoJS.enc.Base64), _key, {
        iv,
        mode: CryptoJS.mode.CTR,
        padding: CryptoJS.pad.Pkcs7
      });
      return decrpted.toString(CryptoJS.enc.Utf8);
    };

    const test = () => {
      const key = "qwer1234qwer1234";
      const data = "hello world";
      const encrypted = encrypt(data, key);
      console.log("加密后: ", encrypted);
      const originStr = decode(encrypted, key);
      console.log("解密后: ", originStr);
    };

    const slots = {
      menu: () => (
        <div class={cssModule.menu}>
          <ElButton type="primary" size="small">
            加 密<i class="iconfont icon-jiami1"></i>
          </ElButton>

          <ElButton type="primary" size="small">
            解 密<i class="iconfont icon-jiemi"></i>
          </ElButton>

          <ElButton type="primary" size="small" onClick={test}>
            测 试<i class="iconfont icon-jiami1"></i>
          </ElButton>

          <ElButton type="success" size="small" disabled={!encryptRes.value} onClick={() => useCopy(encryptRes.value)}>
            复制结果
            <i class="iconfont icon-fuzhi"></i>
          </ElButton>
        </div>
      )
    };

    return () => (
      <BothInputTemplate v-model:leftStr={originStr.value} v-model:rightStr={encryptRes.value} v-slots={slots} />
    );
  }
});
